2
2
.
.
1
1
1
1
.
.
6
6
F
F
r
r
o
o
m
m
J
J
S
S
O
O
N
N
-
-
@
@
R
R
e
e
q
q
u
u
e
e
s
s
t
t
B
B
o
o
d
d
y
y
-
-
S
S
e
e
t
t
t
t
e
e
r
r
s
s
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to use @RequestBody Annotation to convert JSON from HTTP Request into Java Object (DTO).
Syntax
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) { ... }
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: @Controller, @RequestMapping, Tomcat Server
MyController
PersonDTO
Postman
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_dto_json_object_setters (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
– Create Class: PersonDTO.java (inside package controllers)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
PersonDTO.java
package com.ivoronline.springboot_dto_json_object_setters.DTO;
public class PersonDTO {
//PROPERTIES
//Not used for Deserialization if there is Constructor or Setters
public String name;
public Integer age;
//SETTERS
//Used for Deserialization if there is no constructor
//Jackson uses reflection to access private setters
private void setName(String name) { this.name = name; }
private void setAge (Integer age ) { this.age = age; }
}
MyController.java
package com.ivoronline.springboot_dto_json_object_setters.controllers;
import com.ivoronline.springboot_dto_json_object_setters.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(@RequestBody PersonDTO personDTO) {
//GET DATA FROM PersonDTO
String name = personDTO.name;
Integer age = personDTO.age;
//RETURN SOMETHING
return name + " is " + age + " years old";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Start Postman
POST
http://localhost:8080/addPerson
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
{
"name" : "John",
"age" : 20
}
Postman
HTTP Response Body
John is 20 years old
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>